import React, {
  useState,
  forwardRef,
  useImperativeHandle,
  useRef,
  ReactNode,
  FC,
} from 'react'
import { Table, Pagination,Typography ,Tooltip, Button, Dropdown ,Menu } from 'antd'
import useService from '@/utils/tableDefinedHook'
import SearchView from '@/components/common/searchForm'
import './index.less';
import moment from 'moment';
import { clearInterval } from 'timers';
let REFSTIME = null;
const { Title, Paragraph, Text } = Typography;
/**
 * 封装列表、分页、多选、搜索组件
 * @param {RefType} ref 表格的实例，用于调用内部方法
 * @param {object[]} columns 表格列的配置
 * @param {function} apiFun 表格数据的请求方法
 * @param {object[]} searchConfigList 搜索栏配置
 * @param {function} beforeSearch 搜索前的操作（如处理一些特殊数据）
 * @param {function} onFieldsChange 处理搜索栏表单联动事件
 * @param {object} extraProps 额外的搜索参数（不在搜索配置内的）
 * @param {function} onSelectRow 复选框操作回调
 * @param {string} rowKey 表格行的key
 * @param {function} sortConfig 自定义表格排序字段
 * @param {function} expandedRowRender 额外的展开行
 * @param {function} onExpand 点击展开图标时触发
 * @param {string} rowClassName 表格行的样式名
 * @param {boolean} small 表格和分页的展示大小
 * @param {string[]} extraPagation 额外的分页大小
 */

interface TableProps {
  columns: object[];
  scrollOption?:object;
  apiFun: (arg0?: unknown[]) => Promise<{}>;
  ref?: RefType;
  searchConfigList?: object[];
  extraProps?: object;
  rowKey?: string;
  rowClassName?: string;
  expendParams?:Object;
  small?: boolean;
  showHeader?: boolean;
  extraPagation?: string[];
  beforeSearch?: (arg0?: unknown) => void;
  onSelectRow?: (arg0?: string[], arg1?: string[]) => void;
  onFieldsChange?: (arg0?: unknown, arg1?: unknown) => void;
  sortConfig?: (arg0?: object) => any;
  expandedRowRender?: () => ReactNode;
  onExpand?: () => void;
  hiddenRefs?:boolean,
}

const TableDefined: FC<TableProps> = forwardRef(
  (props: TableProps, ref: RefType) => {
    /**
     * @forwardRef
     * 引用父组件的ref实例，成为子组件的一个参数
     * 可以引用父组件的ref绑定到子组件自身的节点上.
     */
    const searchForm: RefType = useRef(null)
    const {
      columns,
      apiFun,
      searchConfigList,
      extraProps,
      rowKey,
      rowClassName,
      small,
      showHeader,
      beforeSearch,
      onSelectRow,
      onFieldsChange,
      sortConfig,
      expandedRowRender,
      onExpand,
      expendParams,
      scrollOption,
      hiddenRefs
    } = props
    // 搜索参数,如果有特殊需要处理的参数，就处理
    

    // 初始参数
    const initParams = {
      ...extraProps,
      pageNum: 1,
      pageSize: 10,
      apiParam:{
        ...{
          "paging":{
            pageNum: 1,
            pageSize: 10,
          },
        },
        ...extraProps['apiParam']||{},
      },
      ...expendParams
    }
    // tablecolumns
    const [autoRefs,setautoRefs] = useState(false);
    // 多选框的选择值
    const [selectedKeys, setSelectedKeys] = useState([])
    // 列表所有的筛选参数（包括搜索、分页、排序等）
    const [tableParams, setTableParams] = useState(initParams)
    // 列表搜索参数
    const [searchParams, setSearchParams] = useState([])
    // 列表排序参数
    const [sortParams, setSortParams] = useState({})
    // 列表分页参数
    const [curPageNo, setCurPageNo] = useState(initParams.pageNum)
    const [curPageSize, setCurPageSize] = useState(initParams.pageSize)

    const { loading = false, response = {} }: CommonObjectType = useService(
      apiFun,
      tableParams
    )
    const validData = response?.data?response.data : {}
    // const { list, total } = validData
    
    let list = validData.data||[];
    let total = validData.count||0;
    let rescolumns = validData.columns||[];
    let tablecolumns = [];
    console.log(rescolumns);
    rescolumns.map((e,i)=>{
      try {
        let display_format = e['display_format']?JSON.parse(e['display_format']):{};
        let feild_name = e?.feild_name||e?.column_name;
      let type = display_format['format']&&display_format['format']['render']&&display_format['format']['render']['type']?display_format['format']['render']['type']:'';
      if(!e.is_hide){
        let itemcolum =  {
          title: ()=>{return <div style={{textAlign:'center'}}>{e['title']}</div>},
          align: e.align_type,
          dataIndex: feild_name,
          key: feild_name,
          width:display_format['format']&&display_format['format']['width']||100
        }
        if(display_format['format']&&display_format['format']['fixed']){
          itemcolum['fixed'] = display_format['format']&&display_format['format']['fixed']
        }
        switch(type){
          case 'datetime':
            itemcolum['render'] = (text, record, index)=>{
              let date_format = display_format['format']&& display_format['format']['render']['date_format']||'YYYY-MM-DD';
              // return date_format;
              return moment(text).format(date_format)
            }
            break;
          case 'map':
            
            itemcolum['render'] = (text, record, index)=>{
              let option = display_format['format']&&display_format['format']['render']['option']||false;
              let txttype = typeof(option[text]);
              let color = option[text]&&txttype!='string'&&option[text]['color']?option[text]['color']:'';
              console.log(text);
              try {
                return <div style={color?{'color':color}:{}}>{txttype=='string'&&option[text]?(option[text]||text):option&&option[text]['text']}</div>;
                
              } catch (error) {
                console.log(error);
                console.log(e,i);
                // return <div>{text}</div>
                return <div>1234</div>
              }
            }
            break;
          case 'index':
            itemcolum['render'] = (text, record, index)=>{
              return <div>{index+1}</div>
            }
            break;
          default:
            itemcolum['render'] = (text, record, index)=>{
              return <Tooltip title={text}>
                <div className='ellipsis' style={{width:display_format['format']&&display_format['format']['width']+'px'||'100px'}}>
                {text}
                </div>
            </Tooltip>
            }
            break;
        }
        tablecolumns.push(itemcolum)
      }
      } catch (error) {
        console.log(error);
        console.log(e,i);
      }
      
     

    })
    tablecolumns = tablecolumns.concat(columns);
    // 执行搜索操作
    const handleSearch = (val: object): void => {
      setSearchParams(val)
      setTableParams({
         ...tableParams, ...val, 
         pageNum: 1,
      apiParam:{
        ...{
          "paging":{
            pageNum: 1,
            pageSize : tableParams.pageSize,
          },
        },
        ...extraProps['apiParam']||{},
        ...val||{},
      },...expendParams })
    }

    // 重置列表部分状态
    const resetAction = (page?: number): void => {
      setSelectedKeys([])
      const nextPage = page || curPageNo
      const nextParmas = page === 1 ? {} : { ...searchParams, ...sortParams }
      setCurPageNo(nextPage)
      setTableParams({
        ...initParams,
        ...nextParmas,
        apiParam:{
          ...{
            "paging":{
              pageNum: nextPage,
              pageSize : curPageSize,
            }
          },
          ...extraProps['apiParam']||{},
          ...searchParams||{},
          
        },
        pageNum: nextPage,
        pageSize: curPageSize,
        ...expendParams
      })
    }

    // 列表复选框选中变化
    const onSelectChange = (
      selectedRowKeys: any[],
      selectedRows: any[]
    ): void => {
      setSelectedKeys(selectedRowKeys)
      onSelectRow(selectedRowKeys, selectedRows)
    }
    // 复选框配置
    const rowSelection = {
      selectedRowKeys: selectedKeys,
      onChange: onSelectChange
    }
    // 判断是否有复选框显示
    const showCheckbox = onSelectRow ? { rowSelection } : {}
    // const showCheckbox ={}
    // 展开配置
    const expendConfig = {
      expandedRowRender,
      onExpand,
      rowClassName
    }
    // 判断是否有展开行
    const showExpend = expandedRowRender ? expendConfig : {}

    // 表格和分页的大小
    const tableSize = small ? 'small' : 'middle'
    const pagationSize = small ? 'small' : 'default'

    // 分页、筛选、排序变化时触发
    const onTableChange = (
      pagination: CommonObjectType,
      filters: CommonObjectType,
      sorter: object
    ): void => {
      // 如果有sort排序并且sort参数改变时，优先排序
      const sortObj = sortConfig ? sortConfig(sorter) : {}
      setSortParams(sortObj)

      const { current: pageNum, pageSize } = pagination
      setCurPageNo(pageNum)
      setCurPageSize(pageSize)
      let newParams = {
        ...initParams,
        ...searchParams,
        ...sortObj,
        pageNum,
        pageSize,
        apiParam:{
            ...{
              "paging":{
                pageNum: pageNum,
                pageSize : pageSize,
              }
            },
            ...extraProps['apiParam']||{},
            ...searchParams||{},
         
        },
        ...expendParams
      };
      setTableParams(newParams)
    }

    /**
     * @useImperativeHandle
     * 第一个参数，接收一个通过forwardRef引用父组件的ref实例
     * 第二个参数一个回调函数，返回一个对象,对象里面存储需要暴露给父组件的属性或方法
     */
    useImperativeHandle(ref, () => ({
      // 更新列表
      update(page?: number): void {
        resetAction(page)
      },
      // 更新列表，并重置搜索字段
      resetForm(page?: number): void {
        if (searchForm.current) searchForm.current.resetFields()
        setSearchParams({})
        resetAction(page)
      },
      // 仅重置搜索字段
      resetField(field?: string[]): void {
        return field
          ? searchForm.current.resetFields([...field])
          : searchForm.current.resetFields()
      },
      // 获取当前列表数据
      getTableData(): CommonObjectType[] {
        return list
      }
    }))
    const refsFunc = ()=>{
      if(autoRefs){
        window.clearInterval(REFSTIME);
        setautoRefs(false);
      }else{
        resetAction()
      }
      
      
    }
    const handleMenuClick= num => {
      
      if(REFSTIME!=null){
        window.clearInterval(REFSTIME);
      }

      REFSTIME = setInterval(()=>{
        resetAction()
      },1000*num)
      setautoRefs(true);
    };
    const menus = (
      <Menu>
        {/* <Menu.Item onClick={()=>handleMenuClick(5)}>每5S刷新一次</Menu.Item> */}
        <Menu.Item onClick={()=>handleMenuClick(30)}>每30S刷新一次</Menu.Item>
        <Menu.Item onClick={()=>handleMenuClick(60)}>每60S刷新一次</Menu.Item>
      </Menu>
    );
    return (
      <div>
        {/* 搜索栏 */}
        {searchConfigList.length > 0 && (
          <SearchView
            ref={searchForm}
            config={searchConfigList}
            beforeSearch={beforeSearch}
            handleSearch={handleSearch}
            onFieldsChange={onFieldsChange}
          />
        )} 
        {/* 列表 */}
        <div className={"tableContainer"}>
          <Table
            {...showCheckbox}
            {...showExpend}
            rowKey={rowKey}
            loading={loading}
            dataSource={list}
            columns={tablecolumns}
            onChange={onTableChange}
            size={tableSize}
            scroll={{
              x:scrollOption['x'],
              y:scrollOption['y']?scrollOption["y"]:(window.innerHeight-540)
            }}
            pagination={{
              size: pagationSize,
              total,
              pageSize: tableParams.pageSize,
              current: tableParams.pageNum,
              showQuickJumper: true,
              showSizeChanger: true,
              pageSizeOptions: ['10','20', '50', '100', '200'],
              showTotal: (all) => {
                return <div>
 {
                !hiddenRefs&&<div className='freshen' >


                <Dropdown.Button  onClick={()=>refsFunc()} overlay={menus}>{autoRefs?'停止自动刷新':'刷新'}</Dropdown.Button>
              </div>
              }
                  <span>`共 ${all} 条`</span>
                  </div>
              }
            }}
          />
        </div>
      </div>
    )
  }
)

TableDefined.defaultProps = {
  searchConfigList: [],
  ref: null,
  extraProps: {},
  hiddenRefs:false,
  rowKey: 'id',
  scrollOption:{
    x:'max-content',
  },
  rowClassName: '',
  small: false,
  showHeader: true,
  extraPagation: [],
  beforeSearch: () => {},
  // onSelectRow: () => {},
  onFieldsChange: () => {},
  sortConfig: () => {},
  expandedRowRender: null,
  onExpand: () => {}
}

export default TableDefined


const otherParams = {
  periodId:'202107'
}

const searchParams = {
  name:'翟科'
}

const queryParams = {
  ...searchParams,
  ...otherParams
}
const queryParams1 = {
  ...searchParams,
  otherParams
}